<?php

class Manga_manage_model extends CI_Model {

    var $image_file_path;
    var $image_url_path;

    public function __construct() {
        parent::__construct();

        //Setup location for uploading of manga pages
        $this->image_file_path = realpath(APPPATH . '../assets/img/manga');
        $this->image_url_path = 'assets/img/manga/';
    }

    /*
     * Below methods are about managing all manga 
     * - get_all_manga()
     * - add_manga()
     * - delete_manga()
     * - check_title_exists()
     * - update_total_pages()
     */

    function get_all_manga() {
        $query_str = "SELECT * FROM manga_lists";

        /*
          SELECT ml.manga_id, ml.title, ml.total_pages, mi.full_path
          FROM manga_lists ml, manga_images mi
          WHERE ml.manga_id = mi.manga_id
          AND mi.page_num = 1"
         */

        //TODO: Change page_num to 0 (Cover)

        return $this->db->query($query_str);
    }

    function add_manga($title) {

        $query_str = "INSERT INTO manga_lists (title) VALUES(?)";
        $this->db->query($query_str, $title);

        //Get added id and create manga folder
        $manga_id = $this->db->insert_id();

        $this->image_file_path .= "/$manga_id";

        if (!file_exists($this->image_file_path)) {
            mkdir($this->image_file_path);

            //Create thumbs folder
            $thumb_path = $this->image_file_path . '/thumbs';
            mkdir($thumb_path);

            //Create characters folder
            $char_path = $this->image_file_path . '/chars';
            mkdir($char_path);
        }
    }

    function check_title_exists($title) {
        $query_str = "SELECT title FROM manga_lists WHERE title = ?";
        $result = $this->db->query($query_str, $title);

        if ($result->num_rows() > 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    function delete_manga($manga_id) {
        //Delete manga folder
        $full_path = $this->image_file_path . '\\' . $manga_id;

        delete_files($full_path, TRUE); //TRUE: delete any directories contained within the supplied root path

        if (rmdir($full_path)) {
            //Delete from database
            //Manga name
            $query_str = "DELETE FROM manga_lists WHERE manga_id = ?";
            $this->db->query($query_str, $manga_id);

            //Manga content
            $query_str = "DELETE FROM manga_images WHERE manga_id = ?";
            $this->db->query($query_str, $manga_id);

            //Manga characters
            $query_str = "DELETE FROM characters WHERE manga_id = ?";
            $this->db->query($query_str, $manga_id);

            return TRUE;
        } else {
            return FALSE;
        }
    }

    //If total page is not provided, minus 1 from current total page (when you delete)
    function update_total_pages($manga_id, $total_pages = FALSE) {
        if (!$total_pages) {
            $query_str = 'UPDATE manga_lists SET total_pages = total_pages - 1 WHERE manga_id = ?';
            $this->db->query($query_str, $manga_id);
        } else {
            $query_str = "UPDATE manga_lists SET total_pages = ? WHERE manga_id= ?";
            $this->db->query($query_str, array($total_pages, $manga_id));
        }
    }

    /*
     * Below methods are about managing a manga
     * - upload_page()
     * - upload_char()
     * - get_title()
     * - get_all_pages()
     * - get_all_characters()
     * - get_personality()
     * - get_last_page()
     * - delete_page()
     * - delete_char()
     */

    function upload_page($manga_id, $page) {

        $errors = '';

        $this->image_file_path .= "\\$manga_id";
        $this->image_url_path .= "$manga_id/";

        //Configuration and upload image
        $config = array(
            'allowed_types' => 'jpg|jpeg|png|gif',
            'upload_path' => $this->image_file_path,
            'max_size' => 2000
        );

        $this->load->library('upload', $config);

        if ($this->upload->do_upload('upload_page')) { //name of upload form
            $image_data = $this->upload->data();

            //Get the full path of the uploaded image
            $full_path = $image_data['full_path'];

            //Configuration and create thumb
            $config = array(
                'source_image' => $full_path,
                'new_image' => $this->image_file_path . '/thumbs',
                'maintain_ration' => TRUE,
                'width' => '150',
                'height' => '100'
            );

            $this->load->library('image_lib', $config);
            $this->image_lib->resize();

            //Add image and thumb url path to database
            $image_name = $image_data['raw_name'];
            $image_url = $this->image_url_path . $image_data['file_name'];
            $image_thumb_url = $this->image_url_path . 'thumbs/' . $image_data['file_name'];

            $query_str = "INSERT INTO manga_images (manga_id,page_num,name,full_path,thumb_path) VALUES (?,?,?,?,?)";
            $this->db->query($query_str, array($manga_id, $page, $image_name, $image_url, $image_thumb_url));

            //After upload image, get total page and add to manga table
            $query_str = "SELECT * FROM manga_images WHERE manga_id = ?";
            $total_pages = $this->db->query($query_str, $manga_id)->num_rows();

            //Update total_pages
            $this->update_total_pages($manga_id, $total_pages);
        } else {
            $errors = $this->upload->display_errors();
        }

        return $errors;
    }

    function upload_char($manga_id, $personality) {

        $errors = '';

        //Create path
        $this->image_file_path .="\\$manga_id" . "\\chars";
        $this->image_url_path .= "$manga_id/chars/";

        //Configuration and upload image
        $config_chars = array(
            'allowed_types' => 'jpg|jpeg|png|gif',
            'upload_path' => $this->image_file_path,
            'max_size' => 2000
        );

        $this->load->library('upload', $config_chars);

        //If upload successfully, add data to database else show errors

        if ($this->upload->do_upload('upload_char')) { //upload_char is name at upload form
            //Get characters name (from file name) and add to database
            $image_data = $this->upload->data();
            $image_name = $image_data['raw_name'];
            $image_url = $this->image_url_path . $image_data['file_name'];

            $query_str = "INSERT INTO characters (manga_id,name,full_path,personality_type) VALUES (?,?,?,?)";
            $this->db->query($query_str, array($manga_id, $image_name, $image_url, $personality));
        } else {
            $errors = $this->upload->display_errors();
        }

        return $errors;
    }

    function get_title($manga_id) {
        $query_str = "SELECT title FROM manga_lists WHERE manga_id = ?";
        return $this->db->query($query_str, $manga_id)->row()->title;
    }

    function get_all_pages($manga_id) {
        $query_str = "SELECT * FROM manga_images WHERE manga_id = ? ORDER by page_num ASC";
        return $this->db->query($query_str, $manga_id);
    }

    function get_all_characters($manga_id) {
        $query_str = "SELECT * FROM characters WHERE manga_id = ?";
        return $this->db->query($query_str, $manga_id);
    }

    function get_personality($manga_id) {
        $query_str = "SELECT personality_type FROM characters WHERE manga_id = ?";
        $all_rows = $this->db->query($query_str, $manga_id);
        $avai_personality = array();

        foreach ($all_rows->result() as $row) {
            $avai_personality[] = trim(strtolower($row->personality_type));
        }

        return $avai_personality;
    }

    function get_last_page($manga_id) {
        $query_str = "SELECT MAX(page_num) AS last_page FROM manga_images WHERE manga_id = ?";
        $result = $this->db->query($query_str, $manga_id);
        $page_num = $result->row(0)->last_page;

        return $page_num;
    }

    function delete_page($manga_id, $id) {
        //Get path
        $query_str = "SELECT thumb_path FROM manga_images WHERE image_id = ?";
        $temp = $this->db->query($query_str, $id)->row()->thumb_path;

        $thumb_path = str_replace('assets/img/manga', '', $temp);
        $thumb_path = str_replace("/", "\\", $thumb_path);
        $thumb_path = $this->image_file_path . "\\" . $thumb_path;

        $full_path = str_replace('\thumbs', '', $thumb_path);

        //Delete from path
        if (unlink($full_path) && unlink($thumb_path)) {
            //Delete from database
            $query_str = "DELETE FROM manga_images WHERE image_id = ?";
            $this->db->query($query_str, $id);

            //Update total pages
            $this->update_total_pages($manga_id);
            return TRUE; //deleted
        } else {
            return FALSE; //not delete
        }
    }

    function delete_char($char_id) {

        //Get path
        $query_str = "SELECT full_path FROM characters WHERE character_id = ?";
        $temp = $this->db->query($query_str, $char_id)->row()->full_path;

        $full_path = str_replace('assets/img/manga', '', $temp);
        $full_path = str_replace("/", "\\", $full_path);
        $full_path = $this->image_file_path . '\\' . $full_path;

        if (unlink($full_path)) {
            //Delete from database
            $query_str = "DELETE FROM characters WHERE character_id = ?";
            $this->db->query($query_str, $char_id);
            return TRUE; //deleted;
        } else {
            return FALSE;
        }
    }

}

/* End of file manga_manage_model.php */
/* Location: ./application/models/admin/manga_manage_model.php */